import { shell } from "electron";
import { closeServer, runServer } from "./server";

const { app } = require("electron");
const path = require("path");
const fs = require("fs");
const os = require("os");

export type electronApiSendType = typeof renderElectronApiSend;
export type electronApiInvokeType = typeof renderElectronApiInvoke;
export const renderElectronApiSend = {};

export let desktopPath = {
  path: "",
};

const delDir = (dir: string) => {
  if (!fs.existsSync(dir)) {
    console.log(dir);
    throw new Error("dir does not exist!");
  }
  const list = fs.readdirSync(dir);
  list.forEach((el: string) => {
    const subDir = path.join(dir, el);
    if (fs.statSync(subDir).isDirectory()) {
      delDir(subDir);
    } else {
      fs.unlinkSync(subDir);
    }
  });
  fs.rmdirSync(dir);
};

const template = `
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>标题</title>
    <style>
        *{
            margin: 0px;
            padding: 0px;
        }
    </style>
</head>
<body>
    <!-- replace -->
</body>
</html>
`;
let web;
const createTemplate = () => {
  web = path.join(desktopPath.path, "web");
  if (fs.existsSync(web)) delDir(web);
  fs.mkdirSync(web);
  const res = path.join(web, "res");
  const css = path.join(res, "css");
  const js = path.join(res, "js");
  const img = path.join(res, "img");
  fs.mkdirSync(res);
  fs.mkdirSync(css);
  fs.mkdirSync(js);
  fs.mkdirSync(img);
};

export const renderElectronApiInvoke = {
  init() {
    desktopPath.path = os.homedir();
    // runServer();
    createTemplate();
  },
  write(_: any, content: string) {
    fs.writeFileSync(
      path.join(web, "index.html"),
      template.replace(`<!-- replace -->`, content)
    );
  },
  openDevFolder() {
    shell.openPath(web);
  },
  destroy() {
    closeServer();
  },
};
